package com.itheima.health.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itheima.health.dto.SetmealDTO;
import com.itheima.health.entity.PageResult;
import com.itheima.health.entity.QueryPageBean;
import com.itheima.health.mapper.SetMealMapper;
import com.itheima.health.pojo.CheckGroup;
import com.itheima.health.pojo.CheckItem;
import com.itheima.health.pojo.Setmeal;
import com.itheima.health.service.SetmealService;
import com.itheima.health.utils.aliyunoss.AliyunUtils;
import com.itheima.health.utils.redis.RedisUtil;
import com.itheima.health.utils.resources.RedisConstant;
import com.itheima.health.vo.CheckGroupVO;
import com.itheima.health.vo.SetmealVO;
import org.apache.dubbo.config.annotation.Service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Set;

@Service
@Transactional
public class SetMealService extends ServiceImpl<SetMealMapper, Setmeal> implements SetmealService {
    @Autowired
    private CheckGroupService checkGroupService;
    private SetMealMapper setMealMapper;


    @Override
    public Boolean add(SetmealDTO setmealDTO) {
        Integer id = setmealDTO.getId();
        if (StringUtils.isNotBlank(String.valueOf(id))) {
            //  id不为空，根据 id  删除 中间表数据（修改）
            //baseMapper.deleteCheckItemInfoByGroupId(id);
            baseMapper.deleteCheckGroupInfoBySetmealId(id);
        }
        //id 为空 保存前端传递的数据（新建）
        boolean flag = saveOrUpdate(setmealDTO);
        Integer gid = setmealDTO.getId();
        //录入中间表
        int[] checkgroupIds = setmealDTO.getCheckgroupIds();
        if (checkgroupIds != null && checkgroupIds.length > 0) {
            //  中间表循环录入
            for (Integer checkgroupId : checkgroupIds) {
                //   添加和修改  中间数据录入
                // baseMapper.addCheckGroupIdAndCheckItemId(gid,checkitemId);
                baseMapper.addSetMealAndCheckGroupInfos(gid, checkgroupId);

            }
        }
        return flag;
    }

    @Override
    public void saveSetemal(SetmealDTO setmealDTO) {


    }

    @Override
    public PageResult findPage(QueryPageBean queryPageBean) {
        //   select  * from xxx where is_delete = 0  and  xxx like ?
        //  条件构造出来   Wrapper对象
        QueryWrapper<Setmeal> queryWrapper = new QueryWrapper<Setmeal>();
        queryWrapper.eq("is_delete", 0);
        Page<Setmeal> page = null;
        if (StringUtils.isBlank(queryPageBean.getQueryString())) {
            page = page(new Page<Setmeal>(queryPageBean.getCurrentPage(), queryPageBean.getPageSize()), queryWrapper);
        } else {
            queryWrapper.like("HELPCODE", queryPageBean.getQueryString());
            //   sql   + 追加  sql  where  name like  %?%
            page = page(new Page<Setmeal>(queryPageBean.getCurrentPage(), queryPageBean.getPageSize()), queryWrapper);
        }
        PageResult result = new PageResult(page.getTotal(), page.getRecords());
        return result;

    }

    @Override
    public SetmealDTO findChecked(int id) {
        List<CheckGroup> list = checkGroupService.list();
        int[] checkItemInfoByGroupId = baseMapper.findCheckGroupInfoBySetmealId(id);
        SetmealDTO setmealDTO = new SetmealDTO();
        setmealDTO.setCheckGroups(list);
        setmealDTO.setCheckgroupIds(checkItemInfoByGroupId);
        return setmealDTO;
    }


    /**
     *   该方法： xxl-job 框架调用
     */
    @Override
    public void clearOssObject() {
        //    清理  oss  垃圾图片   该方法 有  xxl-job 去调用
        //  1.  获取 set 集合 所有图片信息
        Set<String> members = RedisUtil.getMembersOfSet(RedisConstant.ALL_SETMEAL_PIC_SET);
        if (members.size() != 0) {
            for (String uuidfilename : members) {
                //   遍历 图片  判断 redis 该图片有没有存在
                boolean existsKey = RedisUtil.existsKey(RedisConstant.SINGLE_PIC + uuidfilename);
                if (existsKey == false) {
                    //   set集合中没找到  redis 对应得图片信息  那么通知 oss删除图片即可
                    AliyunUtils.deleteFile(uuidfilename);
                    String[] split = uuidfilename.split("-");
                    System.out.println("-----阿里云删除垃圾成功----");
                    System.out.println("-----图片ID:"+split[0]+"----");
                    //  set    集合  垃圾图片 删除
                    RedisUtil.removeSetMember(RedisConstant.ALL_SETMEAL_PIC_SET, uuidfilename);
                }
            }
        }
    }

    @Override
    public SetmealVO findSetMealDetail(int id) {
        //  3条 sql
        //  1.  根据套餐id  查询 套餐
        SetmealVO setmealVO = baseMapper.findSetmealById(id);
        // 2  根据 套餐id  查询对应检查组
        List<CheckGroupVO>  checkGroupVOList = baseMapper.findCheckGroupInfosBySetmealId(id);
        // 3  根据检查组id  查询 检查项信息
        for (CheckGroupVO checkGroupVO : checkGroupVOList) {
            List<CheckItem> checkItemList =  baseMapper.findCheckItemsByCheckGroupId(checkGroupVO.getId());
            checkGroupVO.setCheckItemList(checkItemList);
        }
        setmealVO.setCheckGroups(checkGroupVOList);
        return setmealVO;
    }
}
